package com.atguigu.day03;

import com.atguigu.day02.Example2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;

public class Example1 {
    public static void main(String[] args)throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<Example2.Event> streamSource = env.addSource(new Example2.MySource());
        KeyedStream<Example2.Event, String> keyedStream = streamSource.keyBy(x -> x.name);
        WindowedStream<Example2.Event, String, TimeWindow> windowedStream = keyedStream.window(TumblingProcessingTimeWindows.of(Time.seconds(5)));
        SingleOutputStreamOperator<UserViewCountPerWindow> singleOutputStreamOperator = windowedStream.process(new WindowResult());
        singleOutputStreamOperator.print();
        env.execute();
    }
    public static class WindowResult extends ProcessWindowFunction<Example2.Event,UserViewCountPerWindow,String,TimeWindow>{

        @Override
        public void process(String key, Context context, Iterable<Example2.Event> iterable, Collector<UserViewCountPerWindow> collector) throws Exception {
            collector.collect(new UserViewCountPerWindow(
                    key,
                    iterable.spliterator().getExactSizeIfKnown(),
                    context.window().getStart(),
                    context.window().getEnd()
            ));
        }
    }
    public static class UserViewCountPerWindow{
        public String name;
        public Long count;
        public Long startTime;
        public Long stopTime;

        @Override
        public String toString() {
            return "UserViewCountPerWindow{" +
                    "name='" + name + '\'' +
                    ", count=" + count +
                    ", startTime=" + new Timestamp(startTime) +
                    ", stopTime=" + new Timestamp(stopTime) +
                    '}';
        }

        public UserViewCountPerWindow() {
        }

        public UserViewCountPerWindow(String name, Long count, Long startTime, Long stopTime) {
            this.name = name;
            this.count = count;
            this.startTime = startTime;
            this.stopTime = stopTime;
        }
    }
}
